package org.duncan.Math2D;

import zilvic.resources.ByteMagic;
import zilvic.resources.Parsable;

/**
 *
 * @author Duncan
 */
public final class Point2D implements Parsable {
    private double x, y;

    public Point2D(double x, double y) {
        setX(x);
        setY(y);
    }

    public Point2D setX(double x) {
        this.x = x;
        return this;
    }

    public Point2D setY(double y) {
        this.y = y;
        return this;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public Point2D add(Point2D p) {
        setX(getX() + p.getX());
        setY(getY() + p.getY());
        return this;
    }

    public Point2D reverse() {
        setX(-getX());
        setY(-getY());
        return this;
    }

    @Override
    public Point2D clone() {
        return new Point2D(getX(), getY());
    }

    /**
     * The format is as follows.
     * 0:  The x coordinate (double).
     * 1:  The y coordinate (double).
     * @return This point in bytes.
     */
    public byte[] toBytes() {
        return ByteMagic.compressBytes(new byte[][] {
            ByteMagic.doubleToBytes(getX()),
            ByteMagic.doubleToBytes(getY())});
    }

    public void fromBytes(byte[] bytes) {
        byte[][] u = ByteMagic.uncompressBytes(bytes);
        setX(ByteMagic.bytesToDouble(u[0]));
        setY(ByteMagic.bytesToDouble(u[1]));
    }
}